package com.xiaoq.matrix.service.impl;

import com.xiaoq.ESIndexNameProperties;
import com.xiaoq.coms.util.JsonUtil;
import com.xiaoq.coms.util.MapUtil;
import com.xiaoq.matrix.entity.ContentElementEntity;
import com.xiaoq.matrix.entity.ContentEntity;
import com.xiaoq.matrix.entity.ContentMediaEntity;
import com.xiaoq.matrix.repository.IContentElementRepository;
import com.xiaoq.matrix.repository.IContentMediaRepository;
import com.xiaoq.matrix.repository.IContentRepository;
import com.xiaoq.matrix.service.IContentService;
import com.xiaoq.matrix.toutiao.util.TouTiaoArticle;
import com.xiaoq.matrix.toutiao.util.TouTiaoArticleStatus;
import com.xiaoq.matrix.vo.ContentAndElementVo;
import com.xiaoq.matrix.vo.ElementSyncResultVo;
import com.xiaoq.matrix.vo.PublishResultVo;
import com.xiaoq.matrix.vo.PublishTaskVo;
import com.xiaoq.matrix.weibo.util.ArticleStatus;
import com.xiaoq.matrix.weibo.util.WeiBoUtil;
import com.xiaoq.matrix.weixin.WXAddMaterialResponse;
import com.xiaoq.matrix.weixin.WXMassMsgResponse;
import com.xiaoq.matrix.weixin.util.WeiXinMaterialVo;
import com.xiaoq.matrix.weixin.util.WeiXinUtil;
import com.xiaoq.vo.PagingVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.MessageFormat;
import java.util.*;

@Component
public class ContentServiceImpl implements IContentService {

	private static final Logger LOG = LoggerFactory.getLogger(ContentServiceImpl.class);

	private static final String PUB_QUEUE_NAME = "matrix.content.pub";

	private static final String URL_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
	private static final String URL_MASS_MSG = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token={0}";
	private static final String URL_MASS_MSG_PREVIEW = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token={0}";

	private static final String URL_UPLOAD_IMAGE = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={0}";
	private static final String URL_UPLOAD_TMP_MEDIA = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}";
	private static final String URL_GET_TMP_MEDIA = "https://api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}";
	private static final String URL_ADD_MATERIAL = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}";
	private static final String URL_GET_MATERIAL = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token={0}";
	private static final String URL_ADD_NEWS = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={0}";
	private static final String URL_GET_NEWS = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={0}";
	private static final String URL_GET_MATERIAL_COUNT = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token={0}";

	@Autowired
	private RabbitTemplate mqTpl;

	@Autowired
	private IContentRepository contentRep;

	@Autowired
	private IContentMediaRepository contentRe;

	@Autowired
	private IContentElementRepository elemRepo;

	@Autowired
	private ElasticsearchTemplate template;

	@Autowired
	private ESIndexNameProperties indexNameProperties;

	private Logger logger = LoggerFactory.getLogger(ContentServiceImpl.class);

	@Override
	public List<ContentEntity> findContentElementList(ContentAndElementVo contentAndElementVo, PagingVo pv) {

		return contentRep.findContentList(contentAndElementVo, pv);
	}

	@Override
	public boolean addContent(ContentEntity content) {

		return contentRep.addContent(content);
	}

	@Override
	public ContentEntity findContent(String id) {
		return contentRep.findContentEntity(id);
	}

	@Override
	public boolean delContent(String id) {

		return contentRep.delContent(id);
	}

	@Override
	public boolean updateContent(ContentEntity content) {

		return contentRep.updateContent(content);
	}

	@Override
	public List<ContentEntity> findContentListByCity(String city, String district,PagingVo pv) {

		return contentRep.findContentListByCity(city,district, pv);
	}

	@Override
	public List<ContentEntity> findContentListByCity(String city, String district, String catalogCode, PagingVo pv) {
		return contentRep.findContentListByCity(city,district,catalogCode,pv);
	}

	@Override
	public void sendPublishMessage(String msg) {
		mqTpl.convertAndSend(PUB_QUEUE_NAME, msg);
	}

	@Override
	public void doPublish(PublishTaskVo task) {
		ContentEntity entity = contentRep.findContentEntity(task.getContentId());
		if (entity == null) {
			LOG.error("未知内容ID，" + task.getContentId());
			return;
		}

		List<PublishResultVo> resultList = entity.getPubStatusDetail();
		if (resultList == null) {
			resultList = new ArrayList<>();
			entity.setPubStatusDetail(resultList);
			resultList.add(new PublishResultVo("新浪微博", "未发布"));
			resultList.add(new PublishResultVo("微信", "未发布"));
			resultList.add(new PublishResultVo("今日头条", "未发布"));
		}
		List<String> accessTokenList = task.getAccessTokenList();
		int idx = 0;
		boolean success = false;
		int ok = 0;
		int ng = 0;
		entity.setShareStatus("0");

		contentRep.save(entity);

		for (String mediaId : task.getMediaIdList()) {
			ContentMediaEntity contentMedia = contentRe.getContentMediaById(mediaId);
			if (contentMedia != null) {
				String mediaName = contentMedia.getName();
				success = publish2Media(mediaName, entity, accessTokenList.get(idx));
				idx++;
				if (success) {
					ok++;
				} else {
					ng++;
				}
			}
		}

		if (ok == 0) {
			entity.setShareStatus("1");
		} else {
			if (ng == 0) {
				entity.setShareStatus("2");
			} else {
				entity.setShareStatus("3");
			}
		}
		entity.setPubStatus("2");
		contentRep.save(entity);

	}

	private PublishResultVo findPublishResultVo(String mediaName, List<PublishResultVo> resultList) {
		
		for (PublishResultVo vo : resultList) {
			if (mediaName.equals(vo.getMedia())) {
				return vo;
			}
		}
		return null;
	}

	private boolean publish2Media(String mediaName, ContentEntity entity, String token) {
		boolean pubOk = false;
		switch (mediaName) {
		case "新浪微博":
			pubOk = publish2Weibo(findPublishResultVo(mediaName, entity.getPubStatusDetail()), entity, token);
			break;
		case "微信":
			LOG.info("微信发文时的Token--"+token);
			pubOk = publishWeixin2(findPublishResultVo(mediaName, entity.getPubStatusDetail()), entity, token);
			break;
		case "今日头条":
			pubOk = publish2Toutiao(findPublishResultVo(mediaName, entity.getPubStatusDetail()), entity, token);
			break;
		default:
			break;
		}

		contentRep.save(entity);
		return pubOk;
	}

	private boolean publish2Toutiao(PublishResultVo resultVo, ContentEntity entity, String token) {
		Map<String, String> touTiaoParam = new HashMap<>();
		String title = entity.getTitle();
		if(title.length()>20){
			title = title.substring(20);
		}
		touTiaoParam.put("title", entity.getTitle());
		String detailInfo = entity.getDetailInfo();
		String content = WeiXinTransforUtil.removeEleByKey(detailInfo, "a"); // 滤掉所有超链接
		touTiaoParam.put("content", content);
		touTiaoParam.put("abstract", entity.getIntroduction());
		touTiaoParam.put("save", "1");  //0存草稿，1发布
		// touTiaoParam.put("article_tag", touTiaoVo.getArticle_tag());
		touTiaoParam.put("access_token", token);

		TouTiaoArticleStatus status = TouTiaoArticle.updateStatus(touTiaoParam);
		if (status != null) {
			String msg = status.getMessage();
			if (msg.equals("error")) {
				String errorMsg = "错误码：" + msg + "错误信息：" + status.getData();
				LOG.error("错误信息：" + errorMsg);
				resultVo.setStatus("失败");
				resultVo.setErrMsg(errorMsg);
				return false;

			} else {
				resultVo.setStatus("成功");
				resultVo.setErrMsg(null);
				return false;
			}

		} else {
			String errorMsg = "头条返回状态返回结果为空";
			resultVo.setStatus("失败");
			resultVo.setErrMsg(errorMsg);
			return false;
		}

	}

	private static final class ElementInfo {
		private String url;
		private String type;
		private String urlOfMedia;
		
		

		public String getUrl() {
			return url;
		}

		public void setUrl(String url) {
			this.url = url;
		}

		public String getType() {
			return type;
		}

		public void setType(String type) {
			this.type = type;
		}

		public String getUrlOfMedia() {
			return urlOfMedia;
		}

		public void setUrlOfMedia(String urlOfMedia) {
			this.urlOfMedia = urlOfMedia;
		}

		public ElementInfo() {
			super();
		}

		public ElementInfo(String url, String type) {
			this.url = url;
			this.type = type;
		}
	}

	private HashMap<String, ElementInfo> parseElements(String html) {
		return new HashMap<String, ElementInfo>();
	}

	private static enum WeixinMaterialType {
		IMAGE("image"), VIDEO("video"), VOICE("voice"), NEWS("news");
		private String value;

		WeixinMaterialType(String value) {
			this.value = value;
		}

		public String getValue() {
			return this.value;
		}
	}

	private WeixinMaterialType getMaterialType(String elemType) {
		if ("image".equals(elemType)) {
			return WeixinMaterialType.IMAGE;
		}
		if ("vedio".equals(elemType)) {
			return WeixinMaterialType.VIDEO;
		}
		return WeixinMaterialType.IMAGE;
	}

	private static class QiNiuAcessException extends RuntimeException {
		public QiNiuAcessException(String msg) {
			super(msg);
		}
	}

	private File downloadFromQiNiu(ContentElementEntity cee) {
		HttpHeaders headers = new HttpHeaders();
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
		HttpEntity<String> httpEntity = new HttpEntity<>(headers);
		ResponseEntity<byte[]> response = new RestTemplate().exchange(cee.getUrl(), HttpMethod.GET, httpEntity,
				byte[].class);
		String msg = null;
		File tmpFile = null;
		if (response.getStatusCode() == HttpStatus.OK) {
			try {
				tmpFile = File.createTempFile("xiaoq-matrix-elem-" + System.currentTimeMillis(), cee.getExt());
				Files.write(tmpFile.toPath(), response.getBody());
			} catch (IOException e) {
				msg = "从七牛下载资源时，保存临时文件出错";
				LOG.error(msg, e);
				throw new QiNiuAcessException(msg);
			}
		} else {
			msg = "从七牛下载资源时，出现未知错误，响应码" + response.getStatusCodeValue();
			LOG.error(msg);
			throw new QiNiuAcessException(msg);
		}
		return tmpFile;
	}

	private ElementSyncResultVo syncItem(ContentElementEntity cee, String token) {
		ElementSyncResultVo resultVo = new ElementSyncResultVo();
		File tmpFile = null;
		try {
			tmpFile = downloadFromQiNiu(cee);
		} catch (Exception e) {
			resultVo.setErrMsg(e.getMessage());
			resultVo.setStatus("失败");
			return resultVo;
		}
		RestTemplate rest = new RestTemplate();
		FileSystemResource resource = new FileSystemResource(tmpFile);
		MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
		param.add("media", resource);
		String respStr;
		try {
			respStr = rest.postForObject(
					MessageFormat.format(URL_ADD_MATERIAL, token, getMaterialType(cee.getType()).value), param,
					String.class);
		} catch (Exception e) {
			resultVo.setErrMsg(e.getMessage());
			resultVo.setStatus("失败");
			return resultVo;
		}
		try {
			WXAddMaterialResponse wxObj = JsonUtil.asObject(respStr, WXAddMaterialResponse.class);
			resultVo.setIdOfMedia(wxObj.getMediaId());
			resultVo.setMedia("微信");
			resultVo.setUrlOfMedia(wxObj.getUrl());
			resultVo.setStatus("成功");
			return resultVo;
		} catch (Exception e) {
			resultVo.setErrMsg(e.getMessage());
			resultVo.setStatus("失败");
			return resultVo;
		}
	}

	private WXAddMaterialResponse addNews(String title, String thumbUrl, String author, String digest, String content,
			String srcUrl, String token) {
		RestTemplate rest = new RestTemplate();
		if (digest == null) {
			digest = "";
		} else if (digest.length() > 32) {
			// TODO 微信的摘要有长度限制，具体长度还没查到资料，先设置为32吧
			digest = digest.substring(0, 32);
		}
		Map<String, Object> article = MapUtil.buildMapKVGen(new Object[][] { { "title", title },
				{ "thumb_media_id", thumbUrl }, { "author", author }, { "digest", digest == null ? "" : digest }, { "show_cover_pic", 1 },
				{ "content", content == null ? "" : content }, { "content_source_url", srcUrl == null ? "" : srcUrl } },
				String.class, Object.class);

		Map<String, Object> body = MapUtil.buildMapKVGen(new Object[][] { { "articles", new Object[] { article } } },
				String.class, Object.class);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
		HttpEntity<String> reqEntity = new HttpEntity<String>(JsonUtil.asString(body), headers);
		String respStr = rest.postForObject(MessageFormat.format(URL_ADD_NEWS, token), reqEntity, String.class);
		WXAddMaterialResponse wxObj = JsonUtil.asObject(respStr, WXAddMaterialResponse.class);
		return wxObj;
	}

	private WXMassMsgResponse massPubNews(String newsId, String token) {
		RestTemplate rest = new RestTemplate();

		Map<String, String> news = MapUtil.buildMapKVGen(new String[][] { { "media_id", newsId } }, String.class,
				String.class);

		Map<String, Object> filter = MapUtil.buildMapKVGen(new Object[][] { { "is_to_all", true } }, String.class,
				Object.class);

		Map<String, Object> body = MapUtil.buildMapKVGen(
				new Object[][] { { "filter", filter }, { "mpnews", news }, { "msgtype", "mpnews" } }, String.class,
				Object.class);

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
		HttpEntity<String> reqEntity = new HttpEntity<String>(JsonUtil.asString(body), headers);
		WXMassMsgResponse resp = rest.postForObject(MessageFormat.format(URL_MASS_MSG, token), reqEntity,
				WXMassMsgResponse.class);
		return resp;
	}
	
	/**
	 * 我替调原来比较复杂的方式显示后面再考虑
	 * @param resultVo
	 * @param entity
	 * @param token
	 * @return
	 */
	private boolean publishWeixin2(PublishResultVo resultVo, ContentEntity entity, String token){
		String title = entity.getTitle();
		if(StringUtils.isBlank(title)){
			LOG.info("微信分发title为空");
			return false;
		}
		String imgUrl = entity.getImgUrl();
		if(StringUtils.isBlank(imgUrl)){
			LOG.info("微信分发imgUrl为空");
			return false;
		}
		
		String detialInfo = entity.getDetailInfo();
		if(StringUtils.isBlank(detialInfo)){
			LOG.info("微信分发detialInfo为空");
			return false;
		}
		WeiXinMaterialVo weiXinMateriaVo = WeiXinTransforUtil.transForMatrial(imgUrl, token);
		String thumbMediaId = weiXinMateriaVo.getMediaId();
		String digest = entity.getIntroduction();
		String contentDetail = entity.getDetailInfo();
		
		//交换文章内容到微信服务器
		List<String> imgUrlList = WeiXinTransforUtil .parseHomeWebPage(contentDetail);
		Map<String,String> imgMap = WeiXinTransforUtil.downLoadImags(imgUrlList,token);
		String content = WeiXinTransforUtil.replaceWebPageImages(contentDetail, imgMap);
		//************
		content = WeiXinTransforUtil.removeEleByKey(content, "audio"); //滤掉所有音频
		content = WeiXinTransforUtil.removeEleByKey(content, "video");// 滤掉所有视屏
		String contentSrcUrl = entity.getStaticPath();
		if(StringUtils.isEmpty(contentSrcUrl)){
			contentSrcUrl = "https://www.xiaoq.online";
		}
		WeiXinMaterialVo weiXinMaterialVo = WeiXinUtil.addNews(title, thumbMediaId, "", digest, 1, content, contentSrcUrl, token);
		
		String errorCode = weiXinMaterialVo.getErrcode();
		
		String mediaId = weiXinMaterialVo.getMediaId();
		LOG.info("微信图文素材的媒体Id: "+mediaId);
		//TODO 现在只是做了添加图文素材的方法还要调用群发的部分。
		LOG.info("errorCode:"+errorCode);
		if(StringUtils.isNotEmpty(errorCode)){
			String errorMsg = weiXinMaterialVo.getErrmsg();
			resultVo.setStatus("失败");
			resultVo.setErrMsg(errorMsg);
			return false;

		} else {
			WXMassMsgResponse wXMassMsgResponse = WeiXinUtil.massMsgArticle(token, mediaId);
			int errorCode2 = wXMassMsgResponse.getErrCode();
			LOG.info(errorCode2+"");
			resultVo.setStatus("成功");
			resultVo.setErrMsg(null);
			return true;
		}
		
	}

	private boolean publish2Weixin(PublishResultVo resultVo, ContentEntity entity, String token) {
		// TODO 微信待处理
		// 分析内容，抽取图片以及视频对应的html标签，读取其中的url，根据url匹配素材表找到对应的素材
		// 如果对应的素材已经同步到了微信，则继续下一个，如果素材没有同步到微信，则发起素材同步到微信的调用
		// 调用成功后，更新素材同步状态
		// 内容中的所有素材都已经同步到微信后，将内容同步到微信
		String contentDetail = entity.getDetailInfo();
		// 分析需要替换的素材
		Map<String, ElementInfo> elemMap = parseElements(contentDetail);
		// 缩略图也要上传？
		String thumbUrl = entity.getThumbUrl();
		if (StringUtils.isNotBlank(thumbUrl) && !elemMap.containsKey(thumbUrl)) {
			elemMap.put(thumbUrl, new ElementInfo(thumbUrl, "image"));
		}

		if (elemMap != null && !elemMap.isEmpty()) {
			ContentElementEntity cee;
			ElementSyncResultVo result;
			boolean hasFailure = false;
			String msg;
			ElementInfo elem;
			for (String elemUrl : elemMap.keySet()) {
				elem = elemMap.get(elemUrl);
				cee = elemRepo.getByUrl(elemUrl);
				if (cee == null) {
					msg = "发布到微信的文章中不允许使用微信以外的资源";
					result = new ElementSyncResultVo();
					result.setStatus("失败");
					result.setErrMsg(msg);
				} else {
					if ("成功".equals(cee.getSyncStatus())) {
						List<ElementSyncResultVo> statusList = cee.getSyncStatusDetail();
						if (statusList != null && statusList.size() > 0) {
							result = new ElementSyncResultVo();
							result.setStatus("成功");
							result.setMedia("微信");
							result.setIdOfMedia(statusList.get(0).getIdOfMedia());
						} else {
							result = syncItem(cee, token);
						}
					} else {
						result = syncItem(cee, token);
					}
				}
				if (result == null || "失败".equals(result.getStatus())) {
					hasFailure = true;
				}
				elem.setUrlOfMedia(result.getUrlOfMedia());
				cee.setSyncStatusDetail(Collections.singletonList(result));
				elemRepo.save(cee);
			}

			if (hasFailure) {
				resultVo.setStatus("失败");
				resultVo.setErrMsg("同步素材失败");
				return false;
			}
		} else {
			contentDetail = replaceElementUrls(contentDetail, elemMap);
		}

		if (StringUtils.isBlank(resultVo.getIdOfMedia())) {
			// 以前已经发布了图文素材，就可以不用发布了
			WXAddMaterialResponse wxObj;
			try {
				wxObj = addNews(entity.getTitle(), thumbUrl, entity.getMerchantId(), entity.getIntroduction(),
						contentDetail, entity.getStaticPath(), token);
			} catch (Exception e) {
				resultVo.setStatus("失败");
				resultVo.setErrMsg("同步图文消息失败");
				return false;
			}

			if (wxObj.getErrCode() != null) {
				resultVo.setStatus("失败");
				resultVo.setErrMsg("同步图文消息失败，" + wxObj.getErrMsg());
				return false;
			}
			resultVo.setIdOfMedia(wxObj.getMediaId());
			resultVo.setUrlOfMedia(wxObj.getUrl());
		}

		// 暂时只保存素材，群发
		// WXMassMsgResponse massObj;
		// try {
		// massObj = massPubNews(resultVo.getIdOfMedia(), token);
		// } catch (Exception e) {
		// resultVo.setStatus("失败");
		// resultVo.setErrMsg("群发消息失败，" + e.getMessage());
		// return false;
		// }
		//
		// if(massObj.getErrCode() != null) {
		// resultVo.setStatus("失败");
		// resultVo.setErrMsg("群发消息失败，" + massObj.getErrMsg());
		// return false;
		// }

		resultVo.setStatus("成功");
		resultVo.setErrMsg(null);
		return true;
	}

	private String replaceElementUrls(String contentDetail, Map<String, ElementInfo> elemMap) {
		if (elemMap == null || elemMap.isEmpty()) {
			return contentDetail;
		}
		for (String elemUrl : elemMap.keySet()) {
			contentDetail = contentDetail.replaceAll(elemUrl, contentDetail);
		}
		return contentDetail;
	}

	private boolean publish2Weibo(PublishResultVo resultVo, ContentEntity entity, String token) {
		ArticleStatus ars = null;
		try {
			Map<String, String> weiBoParameter = new HashMap<>();
			weiBoParameter.put("title", entity.getTitle());
//			weiBoParameter.put("content", URLEncoder.encode(entity.getDetailInfo(), "UTF-8"));
			weiBoParameter.put("content", entity.getDetailInfo());
			weiBoParameter.put("cover", entity.getImgUrl());
			weiBoParameter.put("summary", entity.getIntroduction());
			weiBoParameter.put("text", entity.getIntroduction());
			weiBoParameter.put("access_token", token);
			ars = WeiBoUtil.updateStatus(weiBoParameter);
			if (ars != null) {
				long code = ars.getCode();
				if (code == 100000L) {
					resultVo.setStatus("成功");
					resultVo.setErrMsg(null);
					return true;
				} else {

					String errorMsg = "错误码：" + code + "错误信息：" + ars.getMsg();
					LOG.error("错误信息：" + errorMsg);
					resultVo.setStatus("失败");
					resultVo.setErrMsg(errorMsg);
					return false;
				}
			} else {
				String errorMsg = "微博返回结果为空";
				LOG.error("错误信息：" + errorMsg);
				resultVo.setStatus("失败");
				resultVo.setErrMsg(errorMsg);
				return false;
			}

//		} catch (UnsupportedEncodingException e) {
		} catch (Exception e) {
			LOG.error("同步到微博上内容的Unicode编码出错", e);
			String errorMsg = "同步到微博上内容的Unicode编码出错";
			resultVo.setStatus("失败");
			resultVo.setErrMsg(errorMsg);
			return false;
		}
	}

	@Override
	public ContentEntity findCotentDetail(String id) {
		
		return contentRep.findContentEntity(id);
	}

	@Override
	public List<ContentEntity> findContentListFromEs(String shopId, String title, PagingVo pv) {
		List<ContentEntity> resultList = new ArrayList<>();
		Pageable pageable = null;
		if(pv != null){
			pageable = new PageRequest(pv.getPn(), pv.getPs());
		}

		BoolQueryBuilder builder =  QueryBuilders.boolQuery().must(QueryBuilders.termQuery("shopId", shopId))
				.must(QueryBuilders.queryStringQuery(title).defaultField("title").analyzer("ik_smart"))
				.must(QueryBuilders.termQuery("pubStatus", "1"));

		SearchQuery searchQuery = new NativeSearchQueryBuilder()
				.withQuery(builder)
				.withIndices(indexNameProperties.getSitesIndexName())
				.withTypes("content")
				.withPageable(pageable)
				.build();

		template.queryForPage(searchQuery, ContentEntity.class, new SearchResultMapper() {
			@Override
			public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
				SearchHit[] searchHits = response.getHits().getHits();
				if(searchHits==null || searchHits.length<1){
					return null;
				}

				for (SearchHit searchHit : response.getHits()) {
					String source = searchHit.getSourceAsString();
					try {
						ContentEntity contentEntity = JsonUtil.asObject(source, ContentEntity.class);
						contentEntity.setId(searchHit.getId());
						resultList.add(contentEntity);
					}catch (Exception e){
						logger.error(e.getMessage(), e);
					}
				}
				return null;
			}
		});
		return resultList;
	}

	@Override
	public void updateContentStatus(String id, String pubStatus) {
		contentRep.updateContentStatus(id, pubStatus);
	}

	@Override
	public List<ContentEntity> findContentListByCity4key(String city,String catalogCode,String key,PagingVo pv) {
		return contentRep.findContentListByCity4key(city,catalogCode,key, pv);
	}
}
